<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="考试名" prop="examName">
        <el-input
          v-model="queryParams.examName"
          placeholder="请输入考试名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="examBeginTime">
        <el-date-picker
          v-model="examBeginTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
           value-format="yyyy-MM-dd hh:mm:ss"
          align="right"
           @change="getTime()"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="发起人" prop="userId">
        <el-select
          clearable
          v-model="queryParams.userId"
          placeholder="请选择发起人"
        >
          <el-option
            v-for="item in users"
            :key="item.userId"
            :label="item.userName"
            :value="'' + item.userId"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:exam:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['exam:exam:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['exam:exam:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['exam:exam:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="examList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考试名" align="center" prop="examName" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="examBeginTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.examBeginTime, "{y}-{m}-{d} {h}:{m}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试时长" align="center" prop="examTime" />
      <el-table-column label="发起人" align="center" prop="userName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:exam:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="show(scope.row)"
            v-hasPermi="['exam:exam:show']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['exam:exam:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="考试名" prop="examName">
          <el-input v-model="form.examName" placeholder="请输入考试名" />
        </el-form-item>
        <el-form-item label="开始时间" prop="examBeginTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.examBeginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考试时长" prop="examTime">
          <el-input-number
            :min="10"
            :max="200"
            v-model="form.examTime"
            placeholder="请输入时长"
          />
        </el-form-item>
        <el-form-item label="试卷" prop="paperId">
          <el-cascader
            :show-all-levels="false"
            v-model="form.paperId"
            :options="exams"
            :props="{ expandTrigger: 'hover' }"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="参考人员" prop="examUsers">
          <el-input
            v-model="form.examStr"
            type="textarea"
            readonly="true"
            placeholder="请选择参考人员"
          />
          <el-button @click="selectUser()">查询</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="选择考试人员"
      :visible.sync="openUser"
      width="70%"
      append-to-body
    >
      <el-form
        :model="queryParamsUser"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryParamsUser.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="用户状态" prop="userState">
          <el-input
            v-model="queryParamsUser.userState"
            placeholder="请输入用户状态"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery1"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery1"
            >重置</el-button
          >
          <el-button size="mini" @click="xuanze()">确定</el-button>
          <el-button size="mini" @click="cencel()">取消</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange1"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学生名称" align="center" prop="userName" />
        <el-table-column
          label="学生状态"
          :formatter="onState"
          align="center"
          prop="userState"
        />
      </el-table>
      <pagination
        v-show="total1 > 0"
        :total="total1"
        :page.sync="queryParamsUser.pageNum"
        :limit.sync="queryParamsUser.pageSize"
        @pagination="getList1"
      />
    </el-dialog>
    <el-dialog
      title="成绩查看"
      :visible.sync="showScore"
      width="500px"
      append-to-body
    >
      <el-table :data="tableScore">
        <el-table-column label="学生名" align="center" prop="userName" />
        <el-table-column label="成绩" align="center" prop="scoreGrade" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listExam,
  getExam,
  delExam,
  addExam,
  updateExam,
  exportExam,
  getCascade,
} from "@/api/exam/exam";
import { listUser1 } from "@/api/qt/user";
import { listUser } from "@/api/system/user";
import { listScore } from "@/api/qt/score";

export default {
  name: "Exam",
  data() {
    return {
      examBeginTime:[],
      //成绩显示
      showScore: false,
      //成绩数据源
      tableScore: [],
      queryParamsUser: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        userState: null,
      },
      //选中参考人员
      userIds: [],
      userNames: "",
      exams: [],
      //用户数据
      users: [],
      // 遮罩层
      loading: true,
      loading1: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      total1: 0,
      // 试卷管理表格数据
      examList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openUser: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examName: null,
        examBeginTime: null,
        examTime: null,
        userId: null,
        examState: null,
        
        minTime:null,
        maxTime:null
      },
      // 用户管理表格数据
      userList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
     getTime(){
       this.queryParams.minTime=this.examBeginTime[0];
       this.queryParams.maxTime=this.examBeginTime[1];
    },
    show(row) {
      this.showScore = true;
      listScore({ examId: row.examId }).then((res) => {
        this.tableScore = res.rows;
      });
    },
    examState(row) {
      if (row.examState == 0) {
        return "已发起";
      } else {
        return "已结束";
      }
    },
    onState(row) {
      if (row.userState === 0) {
        return "正常";
      } else {
        return "锁定";
      }
    },
    xuanze() {
      this.openUser = false;
      this.form.examUsers = this.userIds.join(",");
      this.form.examStr = this.userNames.join(",");
    },
    cencel() {
      this.openUser = false;
      this.userNames = [];
      this.userIds = [];
    },
    // 多选框选中数据
    handleSelectionChange1(selection) {
      this.userIds = selection.map((item) => item.userId);
      this.userNames = selection.map((item) => item.userName);
    },
    /** 重置按钮操作 */
    resetQuery1() {
      this.resetForm("queryForm");
      this.handleQuery1();
    },
    /** 搜索按钮操作 */
    handleQuery1() {
      this.queryParamsUser.pageNum = 1;
      this.getList1();
    },
    selectUser() {
      this.openUser = true;
      this.getList1();
    },
    /** 查询用户管理列表 */
    getList1() {
      this.loading1 = true;
      listUser1(this.queryParams).then((response) => {
        this.userList = response.rows;
        this.total1 = response.total;
        this.loading1 = false;
      });
    },
    getExams() {
      getCascade().then((res) => {
        this.exams = res;
      });
    },
    getUser() {
      listUser().then((res) => {
        this.users = res.rows;
      });
    },
    /** 查询试卷管理列表 */
    getList() {
      this.loading = true;
      listExam(this.queryParams)
        .then((response) => {
          this.examList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .then(() => {
          this.getUser();
          this.getExams();
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        examId: null,
        examName: null,
        examBeginTime: null,
        examTime: null,
        paperId: null,
        userId: null,
        examState: null,
        examUsers: null,
        examStr: null,
        examInt: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.examBeginTime=[];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.examId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "发起考试";
    },
    getDateTime() {
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      return yy + "/" + mm + "/" + dd + " " + hh + ":" + mf + ":" + ss;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row.examTime >= this.getDateTime());
      if (row.examTime >= this.getDateTime()) {
        this.reset();
        const examId = row.examId || this.ids;
        getExam(examId).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改试卷管理";
        });
      } else {
        this.$alert("此考试已超过开始时间，不能修改", "警告", {
          confirmButtonText: "确定",
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.paperId.length == 3) {
            this.form.paperId = this.form.paperId[2];
          }
          if (this.form.examId != null) {
            updateExam(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExam(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const examIds = row.examId || this.ids;
      this.$modal
        .confirm('是否确认删除试卷管理编号为"' + examIds + '"的数据项？')
        .then(function () {
          return delExam(examIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal
        .confirm("是否确认导出所有试卷管理数据项？")
        .then(() => {
          this.exportLoading = true;
          return exportExam(queryParams);
        })
        .then((response) => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
